﻿using System;
using System.Collections.Concurrent;
using System.Net;

namespace Core
{
    internal class TcpSession : Session
    {
        public ConcurrentQueue<MessageBuffer> rpcReceiveMessages = new ConcurrentQueue<MessageBuffer>();

        public ConcurrentQueue<MessageBuffer> requestMessages = new ConcurrentQueue<MessageBuffer>();
        public ConcurrentQueue<MessageBuffer> receiveMessages = new ConcurrentQueue<MessageBuffer>();

        public bool isTranspond;

        public TcpSession(uint sessionID, IPEndPoint iPEndPoint, EntityObject entity, bool isTranspond)
        {
            this.IPEndPoint = iPEndPoint;
            this.SessionID = sessionID;
            this.Entity = entity;
            this.isTranspond = isTranspond;
        }

        public override bool Register(uint sessionID)
        {
            return new RegisterSession(IPEndPoint, sessionID).Publish().isSuccess;
        }

        public override void SendMessage(IMessage message)
        {
            SendMessage(message, 0);
        }

        public override void SendMessage(IMessage message, byte rpcID)
        {
            //TipMessge(message, rpcID);
            var serializeData = new SerializeMessage(message, SessionID, rpcID, isTranspond).Publish();
            SendMessage(serializeData.messageBuffer);
        }

        public void SendMessage(MessageBuffer messageBuffer)
        {
            if (messageBuffer != null)
                requestMessages.Enqueue(messageBuffer);
        }

        private void TipMessge(IMessage message, byte rpcID)
        {
            if (rpcID > 0)
            {
                if (message is IResponseMessage)
                {
                    new CoreTip(TipLevel.Log, $"发送RPC响应：rpcID:{rpcID}, sessionID:{SessionID}, message:{message.GetType()}, time:{DateTime.Now}").Publish();
                }
                else
                {
                    new CoreTip(TipLevel.Log, $"发送RPC请求：rpcID:{rpcID}, sessionID:{SessionID}, message:{message.GetType()}, time:{DateTime.Now}").Publish();
                }
            }
            else
            {
                new CoreTip(TipLevel.Log, $"发送消息：rpcID:{rpcID}, sessionID:{SessionID}, message:{message.GetType()}, time:{DateTime.Now}").Publish();
            }
        }

        public override void Disconnect()
        {
            new DisconnectTcp(IPEndPoint).Publish();
        }

        public override void Dispose()
        {
            base.Dispose();

            while (requestMessages.TryDequeue(out var messageBuffer))
                MessageBuffer.Push(messageBuffer);

            while (receiveMessages.TryDequeue(out var messageBuffer))
                MessageBuffer.Push(messageBuffer);

            while (rpcReceiveMessages.TryDequeue(out var messageBuffer))
                MessageBuffer.Push(messageBuffer);
        }
    }
}
